package top.lyc829.mymusic.ui.fragment.play_list_detail

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import top.lyc829.mymusic.adapter.SongAdapter
import top.lyc829.mymusic.base.BaseViewModel
import top.lyc829.mymusic.model.bean.Playlist
import top.lyc829.mymusic.model.bean.Song
import top.lyc829.mymusic.model.http.MyNetwork
import top.lyc829.mymusic.model.repository.PlayListRepository
import top.lyc829.mymusic.model.repository.SongRepository

class PlayListDetailViewModel : BaseViewModel() {

    private var playListRepository: PlayListRepository =
        PlayListRepository.getInstance(MyNetwork.getInstance())

    private var songRepository: SongRepository =
        SongRepository.getInstance(MyNetwork.getInstance())

    val id: MutableLiveData<Long> by lazy { MutableLiveData() }
    val copywriter: MutableLiveData<String> by lazy { MutableLiveData() }
    val adapter: SongAdapter by lazy { SongAdapter() }

    private val _playListDetail: MutableLiveData<Playlist> by lazy { MutableLiveData() }
    val playlistDetail: LiveData<Playlist> get() = _playListDetail

    private val _songs: MutableLiveData<List<Song>> by lazy { MutableLiveData() }
    val songs: LiveData<List<Song>> get() = _songs



    fun getPlayListDetail(id: Long) {
        launch(true, {
            _playListDetail.value = playListRepository.getPlayListDetail(id)

//            val params = StringBuilder()
//            _playListDetail.value?.trackIds?.forEachIndexed { index, trackId ->
//                params.append(trackId.id)
//                if (index != _playListDetail.value?.trackIds?.size?.minus(1)) {
//                    params.append(",")
//                }
//            }
            val params = _playListDetail.value?.trackIds?.joinToString(separator = ",") {it.id.toString()} ?: "-1"
            val songs = songRepository.getSongs(params)
            val songsUrl = songRepository.getSongsUrl(params)

            songs.forEach {  song ->
                songsUrl.find { url -> url.id == song.id}.let {
                    if (it != null) {
                        song.url = it.url
                    }
                }
            }
            _songs.value = songs
        }, {
            errorLiveData.value = it
        })
    }

}